package com.example.demo.controller;

import com.example.demo.annotation.AuthToken;
import com.xc.roadRisk.common.utils.ResponseUtils;
import com.xc.roadRisk.common.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(value = "文件上传接口", tags = "文件上传接口")
@RestController
public class PhotoController {

    @ApiOperation(value = "图片上传", notes = "图片上传")
    @PostMapping("/SaveSource")
    @AuthToken
    public Response<List> insertSelective(@RequestParam(value = "multipartFile") MultipartFile[] multipartFile) throws IOException {
        String year=null;
        File file=new File("D://ZDRJQYP");
        if (file.exists() == false) {
            file.mkdir();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        year=sdf.format(date);
        file=new File(file+"//"+year);//按年生成文件
        if (file.exists() == false) {
            file.mkdir();
        }
        List<String> stringList=new ArrayList<>();
        for (MultipartFile multipartFile1:multipartFile) {
            String originalFilename = multipartFile1.getOriginalFilename();
            //新的文件名字
            String newFileName = UUID.randomUUID()+year;
            //封装上传文件位置的全路径
            File targetFile = new File(file, newFileName);
            //把本地文件上传到封装上传文件位置的全路径
            try {
                multipartFile1.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            String url = "/" + year + "/" + newFileName;
            stringList.add(url);
            System.out.println(stringList);

        }
        return ResponseUtils.returnObjectSuccess(stringList);
    }
    @ApiOperation(value = "文件下载", notes = "文件下载")
    @PostMapping("/downloadsource/{name}")
    @AuthToken
    public void download(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception{
        try(
                InputStream inputStream = new FileInputStream(new File("D://ZDRJQYP/"+name));
                OutputStream outputStream = response.getOutputStream();){
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename="+name);

            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}
